// +----------------------------------------------------------------------
// | BossHongshi [鸿时互娱管理系统]
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.hongshihuyu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: wgh
// +----------------------------------------------------------------------
const fly=require("flyio")
module.exports = class extends think.cmswing.center {
  async __before() {
    await super.__before();
    // 判断是否登陆
    // await this.weblogin();
    if (!this.is_login) {
      // 判断浏览客户端
      if (this.isMobile) {
        // 手机端直接跳转到登录页面
        return this.redirect('/center/public/login');
      } else {
        return this.redirect('/cmswing/error/login');
      }
    }
  }
  // 我的玩家
  async indexAction() {
    const status = this.para('status') || null;
    const player_id = this.para('id') || null;
    
//    const proxy_id = this.para('proxy_id') || null;
//    const proxy_id1 = this.get('proxy_id') || '';
    
    const userInfo = await this.model('member').find(this.user.uid);
    const proxy_id=userInfo.proxy_id;
    
    console.log('proxy_id ---------:'+proxy_id);
    // 当前位置
    if (!think.isEmpty(status)) {
      this.assign('status', status);
    }
    
    const url='http://47.97.119.70:5166/GameSupport/dn?cmd=getPlayers&agentId='+proxy_id+'&sign=password';
    fly.config.timeout=10000;
	fly.config.parseJson=true;
	fly.interceptors.response.use(
		    (response) => {
		        //只将请求结果的data字段返回
		        return response.data
		    },
		    (err) => {
		        //发生网络错误后会走到这里
		        //return Promise.resolve("ssss")
		    }
	)
    let ret = await fly.get(url).catch(() => false);
	console.log('ret----------------111--:'+ret);
	let playerdata = (ret === false?null:JSON.parse(ret));
	console.log("getPlayers playerdata --:"+JSON.stringify(playerdata));
	let isbind=0;
	const pdata = [];
	if(!think.isEmpty(playerdata)){
        if(!think.isEmpty(playerdata.data.arr)){
            for (const v of playerdata.data.arr) {
			  v.create_time = this.moment(v.create_time).format('lll');
			  const profitlog = await this.model('profit_log').where({user_id:this.user.uid,act_id:v.uid,status:1}).getField('amount');
			  v.profit = think.isEmpty(profitlog)?0:eval(profitlog.join('+'));
			  if(v.agentId==proxy_id){
		    	  isbind=1;
		      }
		      if (!think.isEmpty(player_id)) {
		        if(v.uid==player_id){
		          pdata.push(v);
		        }
		      }else{
		    	  pdata.push(v);
		      }
		  }
        }
	}
    
	console.log("getPlayers pdata --:"+JSON.stringify(pdata));
    this.assign('isbind', isbind);
	this.assign('list', pdata);
	this.assign('totalid', pdata.length);
	this.assign('proxy_id', proxy_id);
	
    
    // 筛选订单
    //console.log('player.js ---------:'+this.user.uid);
    /**
    let map;
    if (think.isEmpty(player_id)) {
        map = {
                status: ['IN', [0,1,2]],
                uid: this.user.uid
              };
    }else{
    	 map = {
                 status: ['IN', [0,1,2]],
                 uid: this.user.uid,
                 player_id: ['LIKE', '%' + player_id + '%']
               };
    }

    const data = await this.model('member_player').where(map).page(this.para('page')).order('bind_time DESC').countSelect();
    const html = this.pagination(data);
    this.assign('pagination', html);
    
    // 未付款统计
    const totalid = await this.model('member_player').where(map).count('id');
    this.assign('totalid', totalid);
    
    this.assign('count', data.count);
    this.assign('list', data.data);
    */
    this.meta_title = '我的玩家';
    
    // 判断浏览客户端
    if (this.isMobile) {
      if (this.isAjax('get')) {
    	
        return this.json(pdata);
      } else {
        this.active = 'player/index';
        return this.display(this.mtpl());
      }
    } else {
      return this.display();
    }
  }
  
  /**
   * 绑定为我的游戏
   */
 
  async bindplayerAction() {
	      const uid = this.get('uid') || null;
	      const proxy_id = this.get('proxy_id') || null;
	      if (think.isEmpty(uid)) {
	        return this.fail('玩家ID为空！');
	      }
	      if (think.isEmpty(proxy_id)) {
		        return this.fail('代理ID为空！');
		  }
	      
	      console.log('绑定玩家--get data111------:'+uid+' -- '+proxy_id);
	      // 用户
	      let  update =false;
	      const url='http://47.97.119.70:5166/GameSupport/dn?cmd=bindByUid&uid='+uid+'&agentId='+proxy_id+'&sign=password';
		  
	      console.log('绑定玩家--get url------:'+url);
	      fly.config.timeout=10000;
	  	  fly.config.parseJson=true;
	  	  
	  	  let ret = await fly.get(url);
	  	  console.log('绑定玩家--ret.data------:'+ret.data);
	  	  let retdata = JSON.parse(ret.data);
	  	  console.log('绑定玩家--retdata.data.result------:'+retdata.data.result);
	  	  console.log('绑定玩家--retdata.data.msg------:'+retdata.data.msg);
	  	  if(retdata.data.result==0){
	  		console.log('绑定玩家--22222222222.msg------:'+retdata.data.msg); 
	        return this.success({name:'绑定成功！'});
	      } else {
	    	console.log('绑定玩家--333333333.msg------:'+retdata.data.msg); 
	        return this.fail('绑定失败！');
	      }
  }

  /**
   * 充值
   */
  async rechargeAction() {
    if (this.isAjax('POST')) {
      const data = this.post();
      if (think.isEmpty(data.recharge_amount)) {
        return this.fail('请输入数量！');
      } else if (!think.isNumberString(data.recharge_amount)) {
        return this.fail('数量类型错误！');
      }
      
      console.log('玩家充值--post data:'+JSON.stringify(data));
      const userInfo = await this.model('member').find(this.user.uid);
      // 用户
      data.user_id = this.user.uid;
      let  update =false;
      fly.config.timeout=10000;
	  fly.config.parseJson=true;
	  fly.interceptors.response.use(
			    (response) => {
			        //只将请求结果的data字段返回
			        return response.data
			    },
			    (err) => {
			        //发生网络错误后会走到这里
			        //return Promise.resolve("ssss")
			    }
		)
	  
//   const update = await this.model('member').where({id: this.user.uid}).update(member);
     if(data.payment=='card'){
    	 console.log('房卡充值--游戏app端开始充值!');
    	 const url='http://47.97.119.70:5166/GameSupport/dn?cmd=addCard&uid='+data.player_id+'&value='+data.recharge_amount+'&sign=password';
	  	 //let ret = await fly.get(url);
		 let ret = await fly.get(url).catch(() => false);
	  	 console.log('房卡充值------------------:'+ret);
         let retjson = (ret === false?null:JSON.parse(ret));
	  	 
	  	 if(retjson!=null&&retjson.data.result==0){
	  		console.log('房卡充值--游戏app端充值成功!');
	  		console.log('房卡充值--游戏代理端开始扣值!');
	  		update = await this.model('member').where({id:data.user_id}).decrement('card_count', data.recharge_amount);
	  		if (update) {
	  			
	  		//0:账户充值，1:提现,2:订单,3:充卡,4:充币,5:返利,6:奖励金币，7:奖励房卡,8:耗卡,9:耗币
	  			const blog = {
	   	                 admin_id: 1,
	   	                 user_id:this.user.uid,
	   	                 type:8,
	   	                 time: new Date().valueOf(),
	   	                 amount: Number(data.recharge_amount),
	   	                 amount_log: Number(userInfo.card_count)-Number(data.recharge_amount),
	   	                 note: userInfo.username+'为玩家:'+data.player_id+'充值， 房卡充值 '+data.recharge_amount+' 张'
	   	               };
	   	        await this.model('balance_log').add(blog);
	   	        
				console.log('房卡充值--游戏代理端扣值成功!');
              return this.success({name:'充值成功！'});
            } else {
				console.log('房卡充值--游戏代理端扣值失败!');
              return this.fail('充值失败！');
            }
			
	  	 }else{
	  		return this.fail('充值失败！');
	  	 }
     }else if(data.payment=='coin'){
		 console.log('金币充值--游戏app端开始充值!');
    	 const url='http://47.97.119.70:5166/GameSupport/dn?cmd=addGold&uid='+data.player_id+'&value='+data.recharge_amount+'&sign=password';
	  	 let ret = await fly.get(url).catch(() => false);
	  	 console.log('金币充值------------------:'+ret);
         let retjson = (ret === false?null:JSON.parse(ret));
	  	 if(retjson!=null&&retjson.data.result==0){
	  		console.log('金币充值--游戏app端充值成功!');
	  		console.log('金币充值--游戏代理端开始扣值!');
    	    update = await this.model('member').where({id:data.user_id}).decrement('coin_count', data.recharge_amount);

            if (update) {
            	//0:账户充值，1:提现,2:订单,3:充卡,4:充币,5:返利,6:奖励金币，7:奖励房卡,8:耗卡,9:耗币
	  			const blog = {
	   	                 admin_id: 1,
	   	                 user_id:this.user.uid,
	   	                 type:9,
	   	                 time: new Date().valueOf(),
	   	                 amount: Number(data.recharge_amount),
	   	                 amount_log: Number(userInfo.card_count)-Number(data.recharge_amount),
	   	                 note: userInfo.username+'为玩家:'+data.player_id+'充值， 金币充值 '+data.recharge_amount+' 枚'
	   	        };
	   	        await this.model('balance_log').add(blog);
			  console.log('金币充值--游戏代理端扣值成功!');
              return this.success({name:'充值成功！'});
            } else {
			  console.log('金币充值--游戏代理端扣值失败!');
              return this.fail('充值失败！');
            }
			
	  	 }else{
	  		return this.fail('充值失败！');
	  	 }
	 }
     
      
    } else {
      // 获取用户信息
      
      const uid = this.get('uid') || null;
      const nickname = this.get('nickname') || null;
      const proxy_id = this.get('proxy_id') || null;
      console.log('recharge get uid ---------:'+uid+'  '+nickname+' '+proxy_id);
//      const memberPlayer = await this.model('member_player').find(id);
      const userInfo = await this.model('member').find(this.user.uid);
      this.assign('uid', uid);
      this.assign('nickname', nickname);
      this.assign('proxy_id', proxy_id);
      this.assign('userInfo', userInfo);
      
      
      this.meta_title = '充值';
      if (this.isMobile) {
        this.active = 'user/index';
        return this.display(this.mtpl());
      } else {
        this.display();
      }
    }
  }
  
//查找我的玩家
  async searchplayerAction() {
	    const player_id = this.para('playerId') || null;
	    console.log('player_id ---------:'+player_id);
	    if (think.isEmpty(player_id)) {
	          return this.fail('玩家游戏ID不能为空！');
	    }else {
			var gameidmember = await this.model('member').where({game_id:player_id}).find();
	        if (!think.isEmpty(gameidmember)) {
	            return this.fail('游戏ID已经注册代理账号，请重新填写！');
	        }
		}
	   
	    fly.config.timeout=10000;
	    fly.config.parseJson=true;
	    fly.interceptors.response.use(
			(response) => {
					        //只将请求结果的data字段返回
				return response.data
			},
			(err) => {
			//发生网络错误后会走到这里
			//return Promise.resolve("ssss")
			}
		)
		const userInfo = await this.model('member').find(this.user.uid);
	    console.log('查询玩家信息--userInfo.proxy_id:'+userInfo.proxy_id);
	    var data ={};
	    //var data ={"agentId":5700913,"cardNum":504,"create_time":1538105016,"goldNum":11506,"nickname":"phil","referrer_uid":1,"uid":334001};
		var pdata={};
		console.log('查询玩家信息--player_id:'+player_id);
		var url='http://47.97.119.70:5166/GameSupport/dn?cmd=getPlayers&agentId='+userInfo.proxy_id+'&sign=password';
	    
		console.log('查询玩家信息--url---------:'+url);
	    let ret = await fly.get(url).catch(() => false);
		console.log('查询玩家信息 ret------------------:'+ret);
		let playerdata = (ret === false?null:JSON.parse(ret));
		
		if(playerdata!=null&&playerdata.data.result==0){
			for (const v of playerdata.data.arr) {
			      if (v.uid==player_id) {
			    	  data = v;
			      }
			}
		}
		console.log('查询玩家信息 data------------------:'+JSON.stringify(data));
		if(think.isEmpty(data)){
			return this.fail('游戏ID不存在，请重新填写！');
		}else{
			var url = 'http://47.97.119.70:5166/GameSupport/dn?cmd=getPlayerByUid&uid='+data.uid+'&sign=password';
			console.log('查询玩家信息--url---------:'+url);
		    let ret = await fly.get(url).catch(() => false);
			console.log('查询玩家信息 purl ret------------------:'+ret);
			let retdata = (ret === false?null:JSON.parse(ret));
			
			if(retdata!=null&&retdata.data.result==0){
				pdata = retdata.data.info;
				pdata.headimgurl = (pdata.headimgurl.indexOf('defaultHead.jpg')!= -1)?'/static/mobile/img/defaultHead.jpg':pdata.headimgurl;
			}
		}
	    // 判断浏览客户端
	    if (this.isMobile) {
	      if (this.isAjax('get')) {
	        //return this.json(data);
	        return this.success(pdata);
	      } else {
	        this.active = 'player/index';
	        return this.display(this.mtpl());
	      }
	    } else {
	      return this.display();
	    }
  }


};
